package com.iscas.green.extralindextest.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.beans.factory.annotation.Value;

import java.time.Duration;

@Configuration
public class RedisConfig {
    
    private static final Logger log = LoggerFactory.getLogger(RedisConfig.class);
    
    @Value("${redis.host}")
    private String redisHost;
    
    @Value("${redis.port}")
    private int redisPort;
    
    @Value("${redis.password}")
    private String redisPassword;
    
    @Value("${redis.database}")
    private int redisDatabase;
    
    @Value("${redis.timeout:5000}")
    private long timeout;
    
    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory() {
        log.info("初始化Redis连接工厂，host={}，port={}", redisHost, redisPort);
        try {
            RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
            redisConfig.setHostName(redisHost);
            redisConfig.setPort(redisPort);
            redisConfig.setPassword(RedisPassword.of(redisPassword));
            redisConfig.setDatabase(redisDatabase);
            
            LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
                    .commandTimeout(Duration.ofMillis(timeout))
                    .shutdownTimeout(Duration.ofMillis(timeout))
                    .build();
            
            LettuceConnectionFactory factory = new LettuceConnectionFactory(redisConfig, clientConfig);
            
            // 强制初始化连接工厂，以便在启动时发现连接问题
            factory.afterPropertiesSet();
            
            return factory;
        } catch (Exception e) {
            log.error("初始化Redis连接工厂失败", e);
            throw e;
        }
    }
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        log.info("初始化RedisTemplate");
        try {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(connectionFactory);
            
            // 设置key的序列化方式
            template.setKeySerializer(new StringRedisSerializer());
            // 设置value的序列化方式
            template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
            
            // 设置hash key的序列化方式
            template.setHashKeySerializer(new StringRedisSerializer());
            // 设置hash value的序列化方式
            template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
            
            template.afterPropertiesSet();
            
            // 测试连接
            template.getConnectionFactory().getConnection().ping();
            log.info("RedisTemplate初始化成功，连接测试正常");
            
            return template;
        } catch (Exception e) {
            log.error("初始化RedisTemplate失败", e);
            throw e;
        }
    }
} 